package com.atguigu.Flink.state;

import com.atguigu.Flink.POJO.WindSpeedSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Flink09_KeyedAggregatingState {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //需求：检测每种传感器的风速，如果连续的两个风速差值为10，就输出报警
        SingleOutputStreamOperator<WindSpeedSensor> ds = env.socketTextStream("hadoop102", 8888)
                .map(
                        line -> {
                            String[] split = line.split(",");
                            return new WindSpeedSensor(split[0], Integer.valueOf(split[1]), Long.valueOf(split[2]));
                        }
                );
            //计算每种传感器的平均风速
                ds.keyBy(
                        k->k.getId()
                ).process(
                        new KeyedProcessFunction<String, WindSpeedSensor, String>() {
                            //声明归约状态
                            private AggregatingState<Integer,Double> aggregatingState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                //初始化状态
                                AggregatingStateDescriptor<Integer, Tuple2<Integer,Integer>, Double> aggregatingStateDescriptor = new AggregatingStateDescriptor<Integer, Tuple2<Integer,Integer>, Double>(
                                        "aggregatingState"
                                        , new AggregateFunction<Integer, Tuple2<Integer, Integer>, Double>() {
                                    @Override
                                    public Tuple2<Integer, Integer> createAccumulator() {
                                        return Tuple2.of(0,0);
                                    }

                                    @Override
                                    public Tuple2<Integer, Integer> add(Integer integer, Tuple2<Integer, Integer> integerIntegerTuple2) {
                                        return Tuple2.of(integerIntegerTuple2.f0+integer,integerIntegerTuple2.f1+1);
                                    }

                                    @Override
                                    public Double getResult(Tuple2<Integer, Integer> integerIntegerTuple2) {
                                        return Double.valueOf(integerIntegerTuple2.f0/integerIntegerTuple2.f1);
                                    }

                                    @Override
                                    public Tuple2<Integer, Integer> merge(Tuple2<Integer, Integer> integerIntegerTuple2, Tuple2<Integer, Integer> acc1) {
                                        return null;
                                    }
                                }
                                        , Types.TUPLE(Types.INT, Types.INT)
                                );
                                aggregatingState = getRuntimeContext().getAggregatingState(aggregatingStateDescriptor);
                            }

                            @Override
                            public void processElement(WindSpeedSensor windSpeedSensor, KeyedProcessFunction<String, WindSpeedSensor, String>.Context context, Collector<String> collector) throws Exception {
                                //将当前传感器的风速加入到状态
                                aggregatingState.add(windSpeedSensor.getSpeed());
                                collector.collect(windSpeedSensor.getId() + "当前传感器的平均风速" + aggregatingState.get());
                            }
                        }
                ).print();



        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
